package jp.co.sansou.android.atnd.activity;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

import jp.co.sansou.android.asynctask.AsyncTaskProgressDialog;
import jp.co.sansou.android.asynctask.IAsyncTaskCallBack;
import jp.co.sansou.android.asynctask.IAsyncTaskDoInBackground;
import jp.co.sansou.android.atnd.R;
import jp.co.sansou.android.atnd.beans.AtndEventBean;
import jp.co.sansou.android.atnd.common.Util;
import jp.co.sansou.android.atnd.db.AtndDao;
import jp.co.sansou.android.atnd.util.AtndEventSearch;
import jp.co.sansou.android.atnd.util.JsonObj4List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class ActAtndRegList extends Activity {

	/** 検索結果表示用ListView */
	private ListView lvwResult;

	/** 検索結果保持リスト */
	private List<AtndEventBean> listResult;

	private IAsyncTaskDoInBackground asyncTaskDoInBackground = new IAsyncTaskDoInBackground() {
		@Override
		public void doInBackground() {
			// 登録済みATND情報の取得
			AtndDao dao = new AtndDao(ActAtndRegList.this);
			List<AtndEventBean> listRegisted = dao.getAtndInfo();

			// 登録済みATND情報を元に最新のATND情報を取得
			AtndEventSearch.Builder builder = new AtndEventSearch.Builder();

			int[] eventIds = new int[listRegisted.size()];
			for (int i = 0; i < listRegisted.size(); i++) {
				eventIds[i] = listRegisted.get(i).getEventId();
			}
			builder.eventId(eventIds);

			builder.count(listRegisted.size());

			AtndEventSearch atndEventSearch = builder.build();

			JSONObject json = atndEventSearch.searchEventResultJson();

			try {
				listResult = JsonObj4List.getEventList(json);
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
	};

	private IAsyncTaskCallBack asyncTaskCallBack = new IAsyncTaskCallBack() {
		@Override
		public void doInBackgroundCallBack() {
			lvwResult.setAdapter(new OrgListAdapter(ActAtndRegList.this,
					listResult));
		}
	};

	private AdapterView.OnItemClickListener lsnrListView = new AdapterView.OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapterview, View view, int i,
				long l) {
			AtndEventBean bean = listResult.get(i);

			Intent intent = new Intent(ActAtndRegList.this, ActAtndDetail.class);

			intent.putExtra(
					AtndEventSearch.AtndEventJsonSubKeys.EVENT_ID.name(),
					bean.getEventId());
			intent.putExtra(AtndEventSearch.AtndEventJsonSubKeys.TITLE.name(),
					bean.getTitle());
			intent.putExtra(
					AtndEventSearch.AtndEventJsonSubKeys.STARTED_AT.name(),
					bean.getStartedAt());
			intent.putExtra(
					AtndEventSearch.AtndEventJsonSubKeys.ENDED_AT.name(),
					bean.getEndedAt());
			intent.putExtra(AtndEventSearch.AtndEventJsonSubKeys.LIMIT.name(),
					bean.getLimit());
			intent.putExtra(AtndEventSearch.AtndEventJsonSubKeys.PLACE.name(),
					bean.getPlace());
			intent.putExtra(AtndEventSearch.AtndEventJsonSubKeys.URL.name(),
					bean.getUrl());
			intent.putExtra(
					AtndEventSearch.AtndEventJsonSubKeys.OWNER_NICKNAME.name(),
					bean.getOwnerNickname());
			intent.putExtra(
					AtndEventSearch.AtndEventJsonSubKeys.DESCRIPTION.name(),
					bean.getDescription());

			startActivity(intent);
		}
	};

	public void setListAdapter(List<AtndEventBean> list) {
		OrgListAdapter adapter = new OrgListAdapter(this, list);
		lvwResult.setAdapter(adapter);
	}

	private void searchAtndInfo() {
		AsyncTaskProgressDialog asyncTaskProgressDialog = new AsyncTaskProgressDialog(
				ActAtndRegList.this, getResources().getString(
						R.string.msg_progress_wait), asyncTaskDoInBackground,
				asyncTaskCallBack);

		asyncTaskProgressDialog.execute();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.atnd_reg_list);

		// 画面コントロールの取得
		lvwResult = (ListView) findViewById(R.id.lvw_result);

		// イベントリスナーの登録
		lvwResult.setOnItemClickListener(lsnrListView);

		searchAtndInfo();
	}

	/**
	 * ATND検索結果のリストに設定する独自Adapterクラスです。
	 *
	 * @author SANSOU SYSTEMS Co.
	 */
	class OrgListAdapter extends ArrayAdapter<AtndEventBean> {
		private LayoutInflater mInflater;

		public OrgListAdapter(Context context, List<AtndEventBean> listDaily) {
			super(context, 0, listDaily);
			mInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {

			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.atnd_event_list_row,
						null);
			}
			AtndEventBean item = this.getItem(position);

			if (item != null) {
				TextView tvwTitle = (TextView) convertView
						.findViewById(R.id.tvw_title);
				TextView tvwAccept = (TextView) convertView
						.findViewById(R.id.tvw_accept);
				TextView tvwYmd = (TextView) convertView
						.findViewById(R.id.tvw_ymd);
				TextView tvwWaiting = (TextView) convertView
						.findViewById(R.id.tvw_waiting);

				tvwTitle.setText(item.getTitle());
				tvwAccept.setText(item.getAccepted() + "／" + item.getLimit());
				tvwWaiting.setText(String.valueOf(item.getWaiting()));

				Date startedAt = Util.formatDateIso8601(item.getStartedAt());
				if (startedAt != null) {
					tvwYmd.setText(Util.dateToStr(startedAt));
				}
			}
			convertView.findViewById(R.id.rtl_left).setVisibility(View.GONE);

			return convertView;
		}
	}
}
